import { Args, Mutation, Query, Resolver, Subscription, ResolveField, Parent } from '@nestjs/graphql';
import { PubSub } from 'apollo-server-express';

import { Author, Post } from '../models/models';
import { PostIdArg, UpvotePostInput } from '../dto/args';
import { AuthorsService } from '../services/authors.service';
import { PostsService } from '../services/posts.service';
import { UseGuards } from '@nestjs/common';
import { GqlAuthGuard } from '../auth/guards/gql-auth.guard';
import { Roles } from '../common/decorator/roles.decorator';

const pubSub = new PubSub();

@Resolver(of => Post)
export class PostsResolver {
    constructor(
        private authorsService: AuthorsService,
        private postsService: PostsService,
    ) { }

    @Query(returns => Post, { name: 'post' })
    @Roles('member')
    async getPost(@Args() args: PostIdArg) {
        const post = await this.postsService.findPostById(args.id);
        return post;
    }

    @ResolveField('author', returns => Author)
    async getAuthor(@Parent() post: Post) {
        console.log(post);
        const { author } = post;
        return await this.authorsService.findAuthorById(author.id);
    }

    @Mutation(returns => Post)
    async upvotePost(@Args('upvotePostData') upvotePostInput: UpvotePostInput) {
        const post = await this.postsService.upvoteById(upvotePostInput);
        pubSub.publish('postupdated', { postupdated: post });
        return post;
    }

    // 前端的订阅接口
    @Subscription(returns => Post)
    postupdated() {
        return pubSub.asyncIterator('postupdated');
    }
} 